package com.zhonglian.education.customerview.seeimg;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.zhonglian.education.utils.ToastUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by yx on 2017/6/28.
 */

public class ImageBrowsePresenter {

    private ImageBrowseView view;
    private List<String> images;
    private int position;
    private String[] imageTypes = new String[]{".jpg", ".png", ".jpeg", "webp"};

    public ImageBrowsePresenter(ImageBrowseView view) {
        this.view = view;
    }

    public void loadImage() {
        Intent intent = view.getDataIntent();
        images = intent.getStringArrayListExtra("images");
//        Log.i("aaaa", "========imgurllist===========" + images.get(0));
        position = intent.getIntExtra("position", 0);
//        Log.i("aaaa", "========position===========" + position);
        view.setImageBrowse(images, position);
    }

    public void saveImage() {
        //利用Picasso加载图片
        final String imageUrl = getPositionImage();
        if (TextUtils.isEmpty(imageUrl)) {
            ToastUtils.showToastApplication("图片地址为空");
            return;
        }
        Picasso.with(view.getMyContext()).load(imageUrl).into(new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

                String imageType = getImageType(imageUrl); //获取图片类型
                final File file = mImageFilePath(imageType);
                //保存图片
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    if (TextUtils.equals(imageType, "jpg")) imageType = "jpeg";
                    imageType = imageType.toUpperCase();//将英文转成大写
                    bitmap.compress(Bitmap.CompressFormat.valueOf(imageType), 100, fos);
                    fos.flush();
                    fos.close();
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            //view.hideOWLoadingView();//隐藏OWLoading
                            ToastUtils.showToastApplication("保存成功"); //Toast
                        }
                    }, 1600);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    ToastUtils.showToastApplication("保存失败");
                    return;
                }

                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(view.getMyContext().getContentResolver(), file.getAbsolutePath(), file.getName(), null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // 最后通知图库更新
                view.getMyContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        });


    }

    public String getPositionImage() {
        return images.get(position);
    }

    public List<String> getImages() {
        return images;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    public String getImageType(String imageUrl) {
        String imageType = "";
        if (imageUrl.endsWith(imageTypes[0])) {
            imageType = "jpg";
        } else if (imageUrl.endsWith(imageTypes[1])) {
            imageType = "png";
        } else {
            imageType = "jpeg";
        }
        return imageType;
    }

    //构建文件夹及  按时间创建了一个空图片
    public static File mImageFilePath(String imgtype) {
        //获得文件夹
        File takeImageFile;
        if (existSDCard()) {
            //SD卡存在
            takeImageFile = new File(Environment.getExternalStorageDirectory(), "/ed_file/");
        } else {//不存在使用机身内存
            takeImageFile = Environment.getDataDirectory();
        }
        if (!takeImageFile.exists()) {//没有就先创建
            takeImageFile.mkdir();
        }
        takeImageFile = createFile(takeImageFile, "IMG_", "." + imgtype);
        return takeImageFile;
    }

    /**
     * 判断SDCard是否可用
     */
    public static boolean existSDCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 根据系统时间、前缀、后缀产生一个文件
     */
    public static File createFile(File folder, String prefix, String suffix) {
        if (!folder.exists() || !folder.isDirectory()) folder.mkdirs();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        String filename = prefix + dateFormat.format(new Date(System.currentTimeMillis())) + suffix;
        return new File(folder, filename);
    }


}
